'''
Created on Jan 20, 2010

@author: christianp
'''
from BruTile.Pointf import Pointf
from BruTile.Extent import Extent

class MapTransform(object):
    
    resolution = 0.0
    origin = Pointf(0,0)
    center = Pointf(0,0)
    width = 0.0
    height = 0.0
    extent = Extent(0,0,1,1)

    def __init__(self, center, resolution, width, height):
        self.center = center
        self.resolution = resolution
        self.width = width
        self.height = height
        self.updateExtent()
    
    def setOrigin(self):
        self.origin = self.center
    
    def setBoudingBox(self, minx, miny, maxx, maxy):
        self.resolution = (maxx - minx) / self.width
        self.center.x = (maxx + minx) / 2
        self.center.y = (maxy + miny) / 2
        self.update_extent()
    
    def getResolution(self):
        return self.resolution
    
    def setResolution(self, resolution):
        self.resolution = resolution
        self.updateExtent()
    
    def setCenter(self, point):
        self.center = point
        self.updateExtent()
    
    def setWidth(self, width):
        self.width = width
        self.updateExtent()
    
    def setHeight(self, height):
        self.height = height
        self.updateExtent()
        
    def worldToMap(self, x, y):
        return Pointf((x - self.extent.getMinX()) / self.resolution, (self.extent.getMaxY() - y) / self.resolution)
    
    def posWithinMap(self, x, y):
        x = max(0, x)
        x = min(self.width, x)
        y = max(0, y)
        y = min(self.height, y)
        return Pointf(x, y)
        
    def mapToWorld(self, x, y):
        x = (self.extent.getMinX() + x * self.resolution)
        y = (self.extent.getMaxY() - (y * self.resolution))
        return Pointf(x, y)
    
    def updateExtent(self):
        span_x = self.width * self.resolution
        span_y = self.height * self.resolution
        self.extent = Extent(self.center.x - span_x * 0.5, self.center.y - span_y * 0.5,
                             self.center.x + span_x * 0.5, self.center.y + span_y * 0.5)